package quq.missq.utils;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import quq.missq.MissQApplication;


/**
 * 图片工具类
 *
 * @author XieWenjun
 */
public class ImageUtil {

    /**
     * 流形式读取资源图片
     */
    public static Bitmap readResource(Context context, int resId) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        options.inPurgeable = true;
        options.inInputShareable = true;
        InputStream is = MissQApplication.getInstance().getResources().openRawResource(resId);
        return BitmapFactory.decodeStream(is, null, options);
    }

    /**
     * 流形式读取资源图片
     */
    public static Bitmap readResource(Context context, int resId, float height) {
        // 读取
        Bitmap bitmap = readResource(context, resId);

        // 剪切
        float dst = height / bitmap.getHeight();
        int dstWidth = (int) (bitmap.getWidth() * dst);
        int dstHeight = (int) (bitmap.getHeight() * dst);
        bitmap = Bitmap.createScaledBitmap(bitmap, dstWidth, dstHeight, true);

        return bitmap;
    }

    /**
     * 流形式读取资源图片
     */
    public static Bitmap readResource(Context context, int resId, int reqWidth, int reqHeight) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(context.getResources(), resId, options);

        options.inSampleSize = calculateZoomSize(options, reqWidth, reqHeight);// 计算图片的缩放值
        options.inJustDecodeBounds = false;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        options.inPurgeable = true;
        options.inInputShareable = true;
        InputStream is = MissQApplication.getInstance().getResources().openRawResource(resId);
        return BitmapFactory.decodeStream(is, null, options);
    }

    /**
     * 流形式读取文件图片
     */
    public static Bitmap readFile(String pathName) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        options.inPurgeable = true;
        options.inInputShareable = true;
        FileInputStream is = null;
        try {
            is = new FileInputStream(pathName);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return BitmapFactory.decodeStream(is, null, options);
    }

    /**
     * 流形式读取文件图片
     */
    public static Bitmap readFile(String pathName, int reqWidth, int reqHeight) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(pathName, options);

        options.inSampleSize = calculateZoomSize(options, reqWidth, reqHeight);
        options.inJustDecodeBounds = false;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        options.inPurgeable = true;
        options.inInputShareable = true;
        FileInputStream is = null;
        try {
            is = new FileInputStream(pathName);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return BitmapFactory.decodeStream(is, null, options);
    }

    // 计算图片的缩放值
    public static int calculateZoomSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        return calculateZoomSize(options.outWidth, options.outHeight, reqWidth, reqHeight);
    }

    // 计算图片的缩放值
    public static int calculateZoomSize(int width, int height, int reqWidth, int reqHeight) {
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) { // 如果图片的宽高 都小于 请求宽高,不压缩比例
            if (width > height) {// 横图，压缩到高度和屏幕一样
                inSampleSize = Math.round((float) height / (float) reqHeight);
            } else { // 长图或方图，压缩到宽度和屏幕一样
                inSampleSize = Math.round((float) width / (float) reqWidth);
            }

            final float totalPixels = width * height; // 压缩比例前的像素点
            final float totalReqPixelsCap = reqWidth * reqHeight * 2; // 计划压缩比例后的像素点*2  (720 * 1280 * 2)
            while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
                inSampleSize++;
            }
        }

        // 原来的压缩方法
        /*
		 * if (height > reqHeight || width > reqWidth) { final int heightRatio =
		 * Math.round((float) height / (float) reqHeight); final int widthRatio
		 * = Math.round((float) width / (float) reqWidth); inSampleSize =
		 * heightRatio < widthRatio ? widthRatio : heightRatio; }
		 */
        return inSampleSize;
    }


    // 读取图片旋转的角度
    public static int readPhotoDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     * 由URI得到文件路径
     */
    public static String getFilePath4Uri(Context context, Uri uri) {
        String filePath = null;
        ContentResolver cr = context.getContentResolver();
        Cursor cursor = cr.query(uri, null, null, null, null);// 根据URI从数据库中找
        if (cursor != null) {
            cursor.moveToFirst();
            filePath = cursor.getString(cursor.getColumnIndex("_data"));
        }
        return filePath;
    }

    /**
     * 释放ImageView的Bitmap
     *
     * @param imageView 图片控件
     * @author XieWenjun
     */
    public static void recycleBitmap(ImageView imageView) {
        if (imageView != null) {
            Drawable drawable = imageView.getDrawable();
            if (drawable != null) {
                if (drawable instanceof BitmapDrawable) {
                    BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
                    Bitmap bitmap = bitmapDrawable.getBitmap();
                    if (bitmap != null && !bitmap.isRecycled()) {
                        //	Log.d("回收了", null);
                        bitmap.recycle();
                        bitmap = null;
                    }
                }
            }
        }
        System.gc();
    }

    /**
     * 控件生成Bitmap
     *
     * @param v 控件
     * @return Bitmap
     * @author XieWenjun
     */
    public static Bitmap getViewBitmap(View v) {
        Bitmap bitmap = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        v.draw(canvas);
        if (v.isDrawingCacheEnabled()) {//判断是否启用绘制缓存，是的话取消缓存，清理内存
            v.destroyDrawingCache();
        }
        return bitmap;
    }


    /**
     * 保存 图片
     */
    public static void saveImage(Context context, String imageUrl) {
        try {
            String imagePath = ImageLoadUtil.getPath4Url(context, imageUrl);
            File hdFile = new File(imagePath);
            String savedPath = Environment.getExternalStorageDirectory() + "/MissQ/"
                    + ImageLoadUtil.getName4Url(imageUrl) + ".jpg";
            File savedFile = new File(savedPath);
            if (!savedFile.getParentFile().exists()) {
                savedFile.getParentFile().mkdirs();
            }
            if (savedFile.exists()) {
                Toast.makeText(context, "保存路径:" + savedPath, Toast.LENGTH_SHORT).show();
                return;
            }
            hdFile.renameTo(savedFile);
            if (savedFile.exists()) {
                Toast.makeText(context, "保存路径:" + savedPath, Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(context, "抱歉！保存失败，请重新保存!", Toast.LENGTH_SHORT).show();
            }
        } catch (Throwable e) {
            Toast.makeText(context, "抱歉！保存失败，请重新保存!", Toast.LENGTH_SHORT).show();
        }
    }


    /**
     * 保存Bitmap到
     *
     * @param bitName
     * @param mBitmap
     * @return
     * @author XieWenjun
     */
    public static String saveBitmap(String bitName, Bitmap mBitmap) {
        String filepath = "";
        File file = new File(Environment.getExternalStorageDirectory().getPath() + "/" + bitName + ".jpg");
        filepath = file.getAbsolutePath();
        try {
            file.createNewFile();
        } catch (IOException e) {
            Log.e("在保存图片时出错：", e.toString());
        }
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
        try {
            fOut.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return filepath;
    }

    /**
     * 通知系统相册有更新
     *
     * @param filePath
     * @author XieWenjun
     */
    public static void notifyPhotoChanged(String filePath) {
        ContentValues localContentValues = new ContentValues();
        localContentValues.put("_data", filePath);
        localContentValues.put("description", "save image ---");
        localContentValues.put("mime_type", "image/jpeg");
        ContentResolver localContentResolver = MissQApplication.getInstance().getContentResolver();
        Uri localUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        localContentResolver.insert(localUri, localContentValues);
        // 以防万一
        notifyPhotoChanged();
    }

    // 将Bitmap转换成InputStream
    public static InputStream Bitmap2InputStream(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        InputStream is = new ByteArrayInputStream(baos.toByteArray());
        return is;
    }

    // 将Bitmap转换成InputStream
    public static InputStream Bitmap2InputStream(Bitmap bm, int per) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, per, baos);
        InputStream is = new ByteArrayInputStream(baos.toByteArray());
        return is;
    }

    /**
     * 通知系统相册有更新
     */
    public static void notifyPhotoChanged() {
        MediaScannerConnection.scanFile(MissQApplication.getInstance(),
                new String[]{FileUtil.getAppPath().getAbsolutePath()}, null, null);
    }

    public static boolean saveImageToGallery(Context context, Bitmap bmp) {
        if (bmp == null) {

            return false;
        }
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "Miss");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }


        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        }
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(file.getPath()))));
        return true;
    }


}
